package xyz.chaobei.mall.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import xyz.chaobei.mall.model.UmsResourceModel;
import xyz.chaobei.mall.security.component.DynamicAccessDecisionService;
import xyz.chaobei.mall.security.config.SecurityConfig;
import xyz.chaobei.mall.service.UmsAdminService;
import xyz.chaobei.mall.service.UmsResourceService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 继承全局的security config 加载自己的conifg
 *
 * @author <a href='mailto:maruichao52@gmail.com'>MRC</a>
 * @since 2020/10/22
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AdminSecurityConfig extends SecurityConfig {

    @Autowired
    private UmsAdminService adminService;

    @Autowired
    private UmsResourceService resourceService;

    @Bean
    public UserDetailsService loadUserDetail() {
        return username -> adminService.findUserDetailByUserName(username);
    }

    @Bean
    public DynamicAccessDecisionService reloadDynamicAccess() {
        return new DynamicAccessDecisionService() {
            @Override
            public Map<String, ConfigAttribute> loadDataSource() {

                Map<String, ConfigAttribute> map = new HashMap<>();

                List<UmsResourceModel> list = resourceService.findAll();
                list.stream().forEach(item -> map.put(item.getUrl(), new org.springframework.security.access.SecurityConfig(item.getId() + ":" + item.getName())));

                return map;
            }
        };
    }

}
